package com.an.echo;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelPipeline;
import io.netty.util.CharsetUtil;

public class MyHandler extends ChannelInboundHandlerAdapter{

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		
		System.out.println("服务器读取线程：" + Thread.currentThread().getName());
		System.out.println("server ctx :" + ctx);
		System.out.println("channel 和 pipline的关系：");
		Channel channel = ctx.channel();
		ChannelPipeline pipeline = ctx.pipeline();
		ChannelPipeline pipeline2 = channel.pipeline();
		System.out.println("ctx.pipeline():" + pipeline);
		System.out.println("ctx.channel().pipeline():" + pipeline2);
		ByteBuf buf = (ByteBuf) msg;
		System.out.println("客户端发送的消息：" + buf.toString(CharsetUtil.UTF_8));
		System.out.println("客户端地址：" + channel.remoteAddress());
		
		
		
		// 任务队列task
		// 1、用户程序自定义的普通任务
		ctx.channel().eventLoop().execute(()->{
			try {
				TimeUnit.SECONDS.sleep(5);
				ctx.writeAndFlush(Unpooled.copiedBuffer("hello，我来自普通话任务",CharsetUtil.UTF_8));
				System.out.println("普通任务，当前线程：" + Thread.currentThread().getName());
				System.out.println("普通任务，ctx.channel().hashCode():" + ctx.channel().hashCode());
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		});
		
		
		// 用户自定义定时任务
		ctx.channel().eventLoop().scheduleAtFixedRate(()->{
			ctx.writeAndFlush(Unpooled.copiedBuffer("hello，我来自定时任务," + count.getAndIncrement(),CharsetUtil.UTF_8));
			System.out.println("定时任务，当前线程：" + Thread.currentThread().getName());
			System.out.println("定时任务，ctx.channel().hashCode():" + ctx.channel().hashCode());
		}, 5, 5, TimeUnit.SECONDS);
		
		
		
		
		
		
		
	}
	
	// 客户端消息统计
	private AtomicInteger count = new AtomicInteger();
	
	
	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
	
		// 数据读取完毕
		ctx.writeAndFlush(Unpooled.copiedBuffer("hellooo--->>>>" + count.getAndIncrement(),CharsetUtil.UTF_8));
	}
	
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		// 异常就关闭tongdao
		ctx.close();
	}
	
}
